import axios from 'axios';
import { useUserStore } from '@/stores/userStore';

const request = axios.create({
    baseURL: 'http://localhost:8080',
    timeout: 10000
});

// 请求拦截器，自动携带token
request.interceptors.request.use(config => {
    const token = localStorage.getItem('token');
    console.log('请求前token:', token);
    if (token) {
        config.headers.Authorization = 'Bearer ' + token;
        console.log('已设置Authorization:', config.headers.Authorization);
    }
    return config;
}, error => {
    return Promise.reject(error);
});

// 响应拦截器
request.interceptors.response.use(
    response => response.data,
    async error => {
        const originalRequest = error.config;
        const userStore = useUserStore();

        // 处理401未授权错误
        if (error.response?.status === 401 && !originalRequest._retry) {
            originalRequest._retry = true;

            // 检查是否是游客可以访问的公开接口
            const publicUrls = [
                '/api/products',
                '/api/products/banner',
                '/api/auth/login',
                '/api/auth/register'
            ];
            
            const isPublicUrl = publicUrls.some(url => 
                originalRequest.url.includes(url)
            );

            // 如果是公开接口且用户未登录，直接返回错误，不跳转登录
            if (isPublicUrl && !userStore.isAuthenticated) {
                return Promise.reject(error);
            }

            // 如果是已登录用户，尝试刷新令牌
            if (userStore.isAuthenticated && userStore.refreshToken) {
                try {
                    // 尝试刷新令牌
                    const response = await axios.post('/api/auth/refresh', {
                        refreshToken: userStore.refreshToken
                    });

                    // 保存新令牌
                    const newToken = response.data.token;
                    userStore.setToken(newToken);

                    // 重试原始请求
                    originalRequest.headers.Authorization = `Bearer ${newToken}`;
                    return request(originalRequest);
                } catch (refreshError) {
                    // 刷新失败，退出登录
                    userStore.logout();
                    window.location.href = '/login?redirect=' +
                        encodeURIComponent(window.location.pathname);
                }
            } else {
                // 未登录用户访问需要认证的接口，跳转到登录页
                userStore.logout();
                window.location.href = '/login?redirect=' +
                    encodeURIComponent(window.location.pathname);
            }
        }

        return Promise.reject(error);
    }
);

export default request;

// 获取购物车列表
export function getCart() {
    return request.get('/api/cart');
}

// 添加商品到购物车
export function addCartItem({ productId, quantity }) {
    return request.post('/api/cart/add', null, { params: { productId, quantity } });
}

// 更新购物车商品
export function updateCartItem({ itemId, quantity, selected }) {
    return request.post('/api/cart/update', null, { params: { itemId, quantity, selected } });
}

// 删除单个商品
export function deleteCartItem({ itemId }) {
    return request.post('/api/cart/delete', null, { params: { itemId } });
}

// 批量删除
export function batchDeleteCartItems(itemIds) {
    return request.post('/api/cart/batchDelete', itemIds);
}

// 清空购物车
export function clearCart() {
    return request.post('/api/cart/clear');
}

// 合并购物车
export function mergeCart(items) {
    return request.post('/api/cart/merge', items);
}

// 批量结算
export function batchCheckout(itemIds) {
    return request.post('/api/cart/batchCheckout', itemIds);
}

// 获取当前用户信息
export function getUserProfile() {
    return request.get('/api/user/profile');
}

// 修改用户信息
export function updateUserProfile(data) {
    return request.put('/api/user/profile', data);
}

// 修改密码
export function changeUserPassword(data) {
    return request.put('/api/user/password', data);
}

// 用户地址管理相关API
// 获取用户地址列表
export function getUserAddresses() {
    return request.get('/api/user/address');
}

// 添加用户地址
export function addUserAddress(data) {
    return request.post('/api/user/address', data);
}

// 更新用户地址
export function updateUserAddress(data) {
    return request.put(`/api/user/address/${data.addressId}`, data);
}

// 删除用户地址
export function deleteUserAddress(addressId) {
    return request.delete(`/api/user/address/${addressId}`);
}

// 设置默认地址
export function setDefaultUserAddress(addressId) {
    return request.put(`/api/user/address/${addressId}/default`);
}